package com.gyy.flutter.plugin.flutter_plugin_print_a300.common;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by gyy on 2017/3/6. Description
 */
public class BluetoothUtil {

    public static final String NAME = "name";
    public static final String ADDRESS = "address";
    public static final String TYPE = "type";
    //已经连接的设备信息 (壹米设备)
  public static ArrayList<Map<String, String>> addressList = new ArrayList<>();
  //蓝牙adapter
  public static BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

  /**
   * 获取手机连接的蓝牙设备信息
   *
   * @return 空字符串的时候 ，表示蓝牙可正常使用，否则返回异常信息
   */
  public static String getBluetoothAble() {
      String result = "";

      //如果蓝牙未打开 启动蓝牙
      if (!bluetoothAdapter.isEnabled()) {
//          localBluetoothAdapter("连接失败，手机蓝牙未打开");
          result = "蓝牙未开启，请开启蓝牙";
          bluetoothAdapter.enable();
      }

      Set localSet = bluetoothAdapter.getBondedDevices();
      int i = localSet.size();
      if (i > 0) {
        addressList.clear();
        Iterator localIterator = localSet.iterator();
        String macAddress;// 打印机MAC地址
        BluetoothDevice localBluetoothDevice;// 蓝牙设备
        while (localIterator.hasNext()) {
          localBluetoothDevice = (BluetoothDevice) localIterator.next();

          //添加壹米的设备
            String type = "打印机";
            if (!DeviceUtil.isHMDevice(localBluetoothDevice.getName())) {
                continue;
            }
            // 查询数据库保存的记录
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(NAME, localBluetoothDevice.getName());
            map.put(ADDRESS, localBluetoothDevice.getAddress());
            map.put(TYPE, type);
            addressList.add(map);
        }
      } else {
        result = "设备未连接，请连接蓝牙打印机";
      }
    return result;
  }

  /**
   * 得到连接的，默认蓝牙地址 (如果只连接了一个打印机，就选择该打印机)
   *
   * @return the connect address
   */
  public static Map<String, String> getDefaultPrintDevice() {
      //循环添加打印设备
      ArrayList<Map<String, String>> printList = new ArrayList<>();
    if (addressList.size() != 0) {
        for (Map<String, String> device : addressList) {
            if (DeviceUtil.isHMDevice(device.get(NAME))) {
                printList.add(device);
            }
        }
        //只有一个打印设备，默认连接该设备
        if (printList.size() == 1) {
            return printList.get(0);
        }

    }
    return null;
  }



}
